import { Injectable, Inject } from '@nestjs/common';
import { PrismaService } from '@/prisma/prisma.service';
import { PaginationService } from '@/hooks/usePagination';

@Injectable()
export class UserControlService {
  @Inject(PrismaService)
  private readonly prisma: PrismaService;

  @Inject(PaginationService)
  private readonly paginationService: PaginationService;

  async getUserList(pageNum, pageSize, username, hobby, status) {
    const where = {
      status,
      username: {
        contains: username,
      },
    };

    if (hobby.length) {
      where['OR'] = hobby.map((h) => ({
        hobby: {
          contains: h,
        },
      }));
    }

    const query = {
      select: {
        id: true,
        avatar: true,
        username: true,
        phone: true,
        area: true,
        hobby: true,
        status: true,
      },
      where,
    };

    const res = await this.paginationService.paginate(
      'user',
      query,
      pageNum,
      pageSize,
    );

    return res;
  }

  async bannedUser(id: number) {
    const user = await this.prisma.user.findUnique({
      select: {
        id: true,
        status: true,
      },
      where: {
        id,
      },
    });
    if (!user) return '用户不存在';
    const status = user.status === 1 ? 0 : 1;

    try {
      await this.prisma.user.update({
        data: {
          status,
        },
        where: {
          id,
        },
      });
    } catch (e) {
      return '修改失败' + e;
    }
  }
}
